#include <ObjectManager.h>
#include <RenderManager.h>
#include <BaseObject.h>

ObjectManager::ObjectManager()
{
	External::objects = this;
}

ObjectManager::~ObjectManager()
{
	for(unsigned i = 0; i < objects.size(); ++i)
		delete objects[i];
}

void ObjectManager::AddObject( BaseObject* obj )
{
	if(!obj)
		return;

	for(unsigned i = 0; i < objects.size(); ++i)
	{
		if( obj == objects[i] )
			return;
	}

	objects.push_back( obj );
}
		

void ObjectManager::RemoveObject( BaseObject* obj )
{
	deleteList.insert( obj );
}

void ObjectManager::Update(float dt)
{
	unsigned gameSize = objects.size();
	for(unsigned i = 0; i < objects.size(); ++i)
	{
		objects[i]->Update( dt );
		if( gameSize != objects.size() )
		{
			i = 0;
			gameSize = objects.size();
			continue;
		}
	}
}

void ObjectManager::Draw()
{
	External::renderer->Render( External::renderer->renderObjects );
}
		
void ObjectManager::Cleanup()
{
	if( deleteList.empty() )
		return;

	std::set<BaseObject*>::iterator iter = deleteList.begin();
	for(; iter != deleteList.end(); ++iter)
	{
		External::renderer->RemoveRenderObject( (*iter)->gfx );
		ExecuteRemoveObject( *iter );
	}
	deleteList.clear();
}


void ObjectManager::ExecuteRemoveObject( BaseObject* obj )
{
	if(!obj)
		return;

	for(unsigned i = 0; i < objects.size(); ++i)
	{
		if( obj == objects[i] )
		{
			delete objects[i];
			objects[i] = 0;
			objects.erase( objects.begin()+i );
			return;
		}
	}
}